package gri_mime;

use Data::Dumper;
use File::Basename;
use MIME::Base64;

#########################################################################
# Class level variables to record errors of last call.			#
#########################################################################

my $mime_errcode=0;
my $mime_errstr=undef;

sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $self  = {};
my $fname=$_[0];

	$mime_errcode=0;
	$mime_errstr=undef;
	if(! -f $fname) {
		$mime_errcode=1;
		$mime_errstr="File '$fname' does not exist.";
		return undef;
	}
	# Read in all the details ...
	my ($fd,$cline,@F);
	open($fd,$fname);
	if(!defined($fd)) {
		$mime_errcode=2;
		$mime_errstr="Unable to open '$fname': $!";
		return undef;
	}
	$self->{types}={};
	while($cline=<$fd>) {
		chomp $cline;
		@F=split(/\|/,$cline);
		if(@F<4) {
			next;
		}
		$F[4]="ATTACH" if(@F==4 || !defined($F[4]));
		my @F2=split(/,/,$F[0]);
		for my $ct (@F2) {
			$self->{types}->{$ct}=[$F[1],$F[2],$F[3],$F[4]];
		}
	}
	close($fd);
	bless($self,$class);
	return $self;
}

sub error {
	return($mime_errcode,$mime_errstr);
}

sub get_types_list {
my $self=shift;

	return sort(keys %{$self->{types}});
}

# returns the description, mime type, conversion info and attach or not disposition
sub get_type_info {
my $self=shift;
my $type=shift;

	return(undef,undef,undef,undef) if !exists($self->{types}->{$type});
	return(@{$self->{types}->{$type}});
}

sub description {
my $self=shift;
my $filename=shift;

	$mime_errcode=0;
	$mime_errstr=undef;
	my $tail=$filename;
	$tail=~ s/^.*\.//;
	if($tail eq "" || $tail eq $filename) {
		$mime_errcode=3;
		$mime_errstr="Unable to determine file type for '$filename'.";
		return undef;
	}
	if(exists($self->{types}->{lc($tail)})) {
		return $self->{types}->{lc($tail)}->[0];
	}
	$mime_errcode=3;
	$mime_errstr="Unable to determine file type for '$filename'.";
	return undef;
}

sub application {
my $self=shift;
my $filename=shift;

	$mime_errcode=0;
	$mime_errstr=undef;
	my $tail=$filename;
	$tail=~ s/^.*\.//;
	if($tail eq "" || $tail eq $filename) {
		$mime_errcode=3;
		$mime_errstr="Unable to determine file type for '$filename'.";
		return undef;
	}
	if(exists($self->{types}->{lc($tail)})) {
		return $self->{types}->{lc($tail)}->[1];
	}
	$mime_errcode=3;
	$mime_errstr="Unable to determine file type for '$filename'.";
	return undef;
}

sub converter {
my $self=shift;
my $filename=shift;

	$mime_errcode=0;
	$mime_errstr=undef;
	my $tail=$filename;
	$tail=~ s/^.*\.//;
	if($tail eq "" || $tail eq $filename) {
		$mime_errcode=3;
		$mime_errstr="Unable to determine file type for '$filename'.";
		return undef;
	}
	if(exists($self->{types}->{lc($tail)})) {
		return $self->{types}->{lc($tail)}->[2];
	}
	$mime_errcode=3;
	$mime_errstr="Unable to determine file type for '$filename'.";
	return undef;
}

1;
